package com.mybatis.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author KaiJia
 * @DATE 2015-11-10
 * @DESC 简单封装下HttpClient
 */
public class HttpUtil {
    private static final String HTTP_CONTENT_TYPE_JSON = "application/json";
    private static final int CONNECT_TIMEOUT = 5000;// 设置连接建立的超时时间为10s
    private static final int SOCKET_TIMEOUT = 5000;
    private static final int MAX_CONN = 200; // 最大连接数
    private static final int Max_PRE_ROUTE = 150;
    private static final int MAX_ROUTE = 100;
    private static CloseableHttpClient httpClient; // 发送请求的客户端单例
    private static PoolingHttpClientConnectionManager manager; //连接池管理类
    private static ScheduledExecutorService monitorExecutor;

    private final static Object syncLock = new Object(); // 相当于线程锁,用于线程安全

    /**
     * 对http请求进行基本设置
     * @param httpRequestBase http请求
     */
    private static void setRequestConfig(HttpRequestBase httpRequestBase){
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpRequestBase.setHeader("Host","www.mhcb.vip");
        httpRequestBase.setHeader("Accept-Encoding","gzip, deflate");
        httpRequestBase.setConfig(requestConfig);
    }

    public static CloseableHttpClient getHttpClient(String url){
        String hostName = url.split("/")[2];
        int port = 80;
        if (hostName.contains(":")){
            String[] args = hostName.split(":");
            hostName = args[0];
            port = Integer.parseInt(args[1]);
        }

        if (httpClient == null){
            //多线程下多个线程同时调用getHttpClient容易导致重复创建httpClient对象的问题,所以加上了同步锁
            synchronized (syncLock){
                if (httpClient == null){
                    httpClient = createHttpClient(hostName, port);
                    //开启监控线程,对异常和空闲线程进行关闭
                    monitorExecutor = Executors.newScheduledThreadPool(1);
                    monitorExecutor.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            //关闭异常连接
                            manager.closeExpiredConnections();
                            //关闭10s空闲的连接
                            manager.closeIdleConnections(10000, TimeUnit.MILLISECONDS);
                        }
                    }, 5000, 5000, TimeUnit.MILLISECONDS);
                }
            }
        }
        return httpClient;
    }

    /**
     * 根据host和port构建httpclient实例
     * @param host 要访问的域名
     * @param port 要访问的端口
     * @return
     */
    public static CloseableHttpClient createHttpClient(String host, int port){
        ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", plainSocketFactory)
                .register("https", sslSocketFactory).build();

        manager = new PoolingHttpClientConnectionManager(registry);
        //设置连接参数
        manager.setMaxTotal(MAX_CONN); // 最大连接数
        manager.setDefaultMaxPerRoute(Max_PRE_ROUTE); // 路由最大连接数

        HttpHost httpHost = new HttpHost(host, port);
        manager.setMaxPerRoute(new HttpRoute(httpHost), MAX_ROUTE);

        //请求失败时,进行请求重试
        HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                //默认不进行重试
                return false;
            }
        };

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).setRetryHandler(handler).build();
        return client;
    }

    public static String jsonPost(String path, String json, String encoding, String clientIp) {
        // input validate
        if (path == null || json == null || encoding == null) {
            return null;
        }
        String result=null;
        try {

            HttpPost method = new HttpPost(path);
            setRequestConfig(method);

            StringEntity entity = new StringEntity(json, encoding);
            entity.setContentEncoding(encoding);
            entity.setContentType(HTTP_CONTENT_TYPE_JSON);
            method.setEntity(entity);

            if (!StringUtils.isEmpty(clientIp)) {
                method.addHeader("X-Forwarded-For", clientIp);
            }

            HttpResponse httpResponse = getHttpClient(path).execute(method, HttpClientContext.create());
            if (httpResponse == null || httpResponse.getStatusLine() == null) {
                return null;
            }

            if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
                return null;
            }

            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity == null) {
                return null;
            }

            result= EntityUtils.toString(httpEntity, "UTF-8");
            EntityUtils.consume(httpEntity);
            return result;
        } catch (Exception e) {
        }
        return result;
    }

    public static String get(String path, String encoding) {
        // input validate
        if (path == null || encoding == null) {
            return null;
        }
        String result=null;

        try {

            HttpGet method = new HttpGet(path);
            setRequestConfig(method);
            HttpResponse httpResponse = getHttpClient(path).execute(method);
            if (httpResponse == null || httpResponse.getStatusLine() == null) {
                return null;
            }

            if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
                return null;
            }

            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity == null) {
                return null;
            }

            result=EntityUtils.toString(httpEntity, encoding);
            EntityUtils.consume(httpEntity);
            return result;
        } catch (Exception e) {
        }
        return result;

    }


    public static String post(String path, List<NameValuePair> params, String encoding) {
        if (path == null || params == null || encoding == null) {
            return null;
        }
        String result=null;
        try {

            // 设置请求和传输超时时间
            HttpPost method = new HttpPost(path);
            setRequestConfig(method);

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            method.setEntity(entity);


            HttpResponse httpResponse = getHttpClient(path).execute(method);
            System.out.println(JSONObject.toJSONString(httpResponse));
            if (httpResponse == null || httpResponse.getStatusLine() == null) {
                return null;
            }

            if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
                return null;
            }

            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity == null) {
                return null;
            }

            result= EntityUtils.toString(httpEntity, "UTF-8");
            EntityUtils.consume(httpEntity);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
